//
//  LZDealViewController.m
//  tuangou
//
//  Created by quan jimmy on 11-12-10.
//  Copyright 2011年 tencent. All rights reserved.
//

#import "LZDealViewController.h"
#import "LZClient.h"
#import "SBJson.h"
#import "Deal.h"
#import "LZDealCell.h"

#define PAGESIZE 20

@implementation LZDealViewController
@synthesize HUD,dealList,hasMoreData,cateId,dragMoreLabel,activityIndicatorView;

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    LZClient *client = [[LZClient alloc] init];
    [client requestDeal: self.cateId page:1 limit:PAGESIZE tag:TAG_DEAL_LIST delegate:self];
    [client release];
    
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return hasMoreData?[dealList count]+1:[dealList count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (dealList.count ==0) {
        return [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"nilcell"] autorelease];
    }
    
    if (hasMoreData && indexPath.row == dealList.count) {
        static NSString *CellIdentifier = @"Cell";
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        }
        cell.backgroundColor = [UIColor lightGrayColor];
        dragMoreLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 3, 120, 26)];
        dragMoreLabel.textAlignment = UITextAlignmentCenter;
        dragMoreLabel.font = [UIFont systemFontOfSize: 14];
        dragMoreLabel.textColor = [UIColor grayColor];
        dragMoreLabel.text = @"载入信息中";
        [cell.contentView addSubview:dragMoreLabel];
        
        activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
		activityIndicatorView.frame = CGRectMake(80, 6, 20, 20);
        
        [cell.contentView addSubview:activityIndicatorView];
        
//        UIView *hideSeperatorView = [[UIView alloc]init];
//        hideSeperatorView.backgroundColor = [UIColor whiteColor];
//        hideSeperatorView.frame = CGRectMake(0, 31, 320, 2);
//        [cell addSubview:hideSeperatorView];
//        [hideSeperatorView release];
        
        return cell;
    }
    static NSString *CellIdentifier = @"DealCell";
    
    LZDealCell *cell = (LZDealCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[LZDealCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    [cell setDeal:[self.dealList objectAtIndex:indexPath.row]];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == dealList.count) {
        return 32;
    } else return 86;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (hasMoreData && indexPath.row > 0 && indexPath.row == dealList.count) {
        [activityIndicatorView startAnimating];
        [self performSelector:@selector(loadMoreDeal) withObject:nil afterDelay:0.5];
    }
}

- (void)loadMoreDeal {
    
    LZClient *client = [[LZClient alloc] init];
    [client requestDeal:cateId page:(dealList.count/PAGESIZE + 1) limit:PAGESIZE tag:TAG_DEAL_LIST delegate:self];
    [client release];
    
}

//ASIHTTP delegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    if (request.responseStatusCode != 200) {
        [self requestErrorHandle:request.responseStatusCode message:@"http error" tag:request.tag];
        return;
    }
    if (!dealList) {
        dealList = [[NSMutableArray alloc] init];
    }
//    NSMutableArray *deals = [[NSMutableArray alloc] init];
    NSString *response = [request responseString];
    
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSArray *rows = [parser objectWithString:response];
    if (!rows) {
//        [deals release];
        [parser release];
        return;
    }
    for (NSDictionary *row in rows) {
        Deal *deal = [[Deal alloc] initWithDict:row];
        [dealList addObject:deal];
        [deal release];
    }
    [parser release];
    
    if (request.tag == TAG_DEAL_LIST) {
        if ([dealList count]%PAGESIZE == 0) {
            hasMoreData = YES;
        } else hasMoreData = NO;
//        [dealList addObjectsFromArray:deals];
        NSLog(@"dealList count:%d",[dealList count]);
        [dealList retain];
        [HUD hide:YES];
        [self.tableView reloadData]; 
        [activityIndicatorView stopAnimating];
        
    }
//    
//    [deals release];
    
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"error: %@", error);
    [self requestErrorHandle:request.responseStatusCode message:@"http error" tag:request.tag];
}

- (void)requestErrorHandle:(NSInteger)errorCode message:(NSString *)errorMessage tag:(NSInteger)tag {
    if (tag == TAG_CATGORY_LIST) {
        [HUD hide:YES];
        dealList = nil;
        [self.tableView reloadData];
    }
}

- (void)showLoadingDialog
{
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
	[self.navigationController.view addSubview:HUD];
    HUD.labelText = @"加载数据";
    [HUD show:YES];
}

@end
